package com.zhi.syc.data.task

import android.content.Context
import com.zhi.syc.data.ASSycBuilder
import com.zhi.syc.data.http.ASRequestManager
import com.zhi.syc.data.http.ASRequestParams
import com.zhi.syc.data.http.ASUrlHelper
import com.zhi.syc.data.services.ASBatteryService
import java.util.concurrent.CompletableFuture
import java.util.concurrent.CountDownLatch
import java.util.concurrent.Executors
import java.util.function.Supplier

class ASBatteryTask(private val context: Context) : Supplier<String> {

    companion object {
        private const val TASK_ID = "TASK_BATTERY"
    }

    override fun get(): String {
        println("$TASK_ID Running...")

        val url = ASUrlHelper.combineUrl()
        if (url.isNotBlank()) {
            val latch = CountDownLatch(1)
            Executors.newSingleThreadExecutor().submit(AsyncBatteryTask(context, latch, url))
            latch.await()
        }
        return TASK_ID
    }

    private class AsyncBatteryTask(
        private val context: Context,
        private val latch: CountDownLatch,
        private val url: String
    ) : Runnable {

        override fun run() {
            ASBatteryService().get(
                context,
                object : ASBatteryService.OnBatteryInfoListener {
                    override fun onFetchSuccess(zipString: String) {
                        val netParams = ASRequestParams(
                            path = ASSycBuilder.pathBty,
                            deviceBatteryGzip = zipString
                        ).toEncryptParams()
                        val future = CompletableFuture.supplyAsync {
                            ASRequestManager(
                                url = url,
                                body = netParams,
                                taskId = TASK_ID
                            ).doPost()
                            TASK_ID
                        }
                        future.thenRun { latch.countDown() }
                    }
                })
        }
    }
}
